[Coding027] Sort - 词典排序

Lexicographic-sort

Ben 2024/01/20

More coding records

Get the knowledge flowing and circulating! :)

目录

标题:词典排序

Words & phrases

lexicographic 美/ ˌleksɪkəˈɡræfɪk /

  • adj.词典编辑的;字典式的

Lexicographic order is imposed on the namespace declarations and attributes of each element.

对名称空间声明和每个元素中的属性采用词典序。

字典序是指按照单词首字母顺序在字典中进行排序的方法。在数学中可推广到有序符号序列,可视为完全有序集合的元素序列的一种排序方法。

概念

在英文字典中,排列单词的顺序是先按照第一个字母以升序排列(即a、b、c……z 的顺序);如果第一个字母一样,那么比较第二个、第三个乃至后面的字母。如果比到最后两个单词不一样长(比如,sigh 和 sight),那么把短者排在前。

通过这种方法,我们可以给本来不相关的单词强行规定出一个顺序。“单词”可以看作是“字母”的字符串,而把这一点推而广之就可以认为是给对应位置元素所属集合分别相同的各个有序多元组规定顺序。

形式定义

给定两个偏序集 AB(a,b)(a,b) 属于笛卡尔积 A×B,则字典序定义为

(a,b)(a,b)    a<a(a=abb).

结果是偏序。如果 AB 是全序, 那么结果也是全序。

——维基百科

  • Let Ci be the comparator that compares two tuples by their i-th dimension i.e.

    • for C2:

      (x1,x2,x3)(y1,y2,y3) if x2y2
    • for C3:

      (x1,x2,x3)(y1,y2,y3) if x3y3
  • Let stableSort(S, C) be any stable sorting algorithm that uses comparator C

  • Lexicographic-sort sorts a sequence of d-tuples in lexicographic order by executing d times algorithm stableSort, one per dimension

实例

(7, 4, 6) (5, 1, 5) (2, 4, 6) (2, 1, 4) (3, 2, 4)

sort according to left-most dimension

 

注意

Notice that the sorting goes from last to first. Why?

image-20240120114005366

Lexicographic-sort runs in O(dT(n)) time, where T(n) is the running time of stableSort.

 

辨析

lexicographical order:字典顺序:一种排序方法,按照字母表顺序排列单词或字符串。

numerical order:数字顺序:按照数字大小或顺序排列的顺序。

alphabetical order:按字母顺序排列:一组项目(例如字典中的单词)按照字母顺序排列的顺序。

Demo
1, 10, 2
Lexicographical ordering means dictionary order.
For ex: In dictionary 'ado' comes after 'adieu' because 'o' comes after 'i' in English alphabetic system.
This ordering is not based on length of the string, but on the occurrence of the smallest letter first.